package com.aleaho.cftrack.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;


import com.aleaho.cftrack.CFTrackApplication;
import com.aleaho.cftrack.R;
import com.aleaho.cftrack.dialog.TrackAnalysisInfoLayout;
import com.aleaho.cftrack.http.entity.LoginEntity;
import com.aleaho.cftrack.presenter.LocationPresenter;
import com.aleaho.cftrack.utils.BitmapUtil;
import com.aleaho.cftrack.utils.CommonUtil;
import com.aleaho.cftrack.utils.Constants;
import com.aleaho.cftrack.utils.MapUtil;
import com.aleaho.cftrack.utils.TrackConsts;
import com.aleaho.cftrack.utils.ViewUtil;
import com.aleaho.cftrack.view.LocationView;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.trace.api.entity.EntityInfo;
import com.baidu.trace.api.entity.LatestLocation;
import com.baidu.trace.model.Point;

import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;

public class LocationActivity extends BaseActivity implements View.OnClickListener,
        BaiduMap.OnMarkerClickListener, LocationView {


    @BindView(R.id.tv_staff_name)
    TextView tvStaffName;
    @BindView(R.id.mv_location)
    MapView mapView;

    private String tracker = null;
    private String entityName = null;

    private ViewUtil viewUtil = null;
    private MapUtil mapUtil = null;


    private List<String> entities = new LinkedList<>();
    private List<Point> latestPoints = new LinkedList<>();
    private List<Marker> markers = new LinkedList<>();


    private Marker analysisMarker = null;

    private TrackAnalysisInfoLayout trackAnalysisInfoLayout = null;


    private CFTrackApplication trackApp = null;
    private LocationPresenter locationPresenter = null;

    private int pageIndex = 1;
    /**
     * 轨迹分析上一次请求时间
     */
    private long lastQueryTime = 0;


    /**
     * 活跃时间，为当前时间推迟10分钟。
     */
    long activeTime = CommonUtil.getCurrentTime() / 1000 - 10 * 60;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(R.string.activity_location);
        trackApp = (CFTrackApplication) getApplicationContext();

        locationPresenter = new LocationPresenter(trackApp, this, this);

        viewUtil = new ViewUtil();
        initView();
        init();
        queryLatestPoint();
        queryEntityList();
    }


    private void init() {
        mapUtil = new MapUtil();
        mapUtil.init(mapView);
        trackAnalysisInfoLayout = new TrackAnalysisInfoLayout(this, mapUtil.baiduMap);
        mapUtil.baiduMap.setOnMarkerClickListener(this);
    }

    /**
     * 初始化界面。
     */
    private void initView() {
        setBackView();

        LoginEntity le = trackApp.getLoginEntity();

        if (le == null) {
            return;
        }

        if (le.getLoginUser().getPermission().getDutyId() < TrackConsts.WILL_SHOW_MENU_LESS_THAN) {
            Log.i(Constants.TAG, "权限编号：" + le.getLoginUser().getPermission().getDutyId() +
                    "Name:" + le.getLoginUser().getName());
            setRightImage(R.drawable.ic_staff_tree_white_24dp, this);
        }

        this.entityName = trackApp.getEntityName();
        this.entities.clear();
        this.entities.add(entityName);
        this.tracker = le.getLoginUser().getName();

        tvStaffName.setText(le.getLoginUser().getName());
    }

    @Override
    public int getResourcesId() {
        return R.layout.activity_location;
    }

    @Override
    public void onClick(View v) {

        Log.i(Constants.TAG, "位置查询界面点击的view ID为:" + v.getId());

        switch (v.getId()) {
            case R.id.toolbar_righ_iv:
                Intent intent = new Intent(LocationActivity.this,
                        DepartmentTreeActivity.class);
                startActivityForResult(intent, Constants.TRACKER_REQUEST_CODE);
                break;
            default:
                break;
        }
    }


    private void queryLatestPoint() {
        mapUtil.clearMap();
        locationPresenter.queryLatestPoint(entityName);
    }

    private void queryEntityList() {
        locationPresenter.queryEntityList(entities, activeTime, pageIndex);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Constants.TRACKER_RESULT_CODE) {
            return;
        }

        if (data.hasExtra(TrackConsts.TRACKER) && data.hasExtra(TrackConsts.ENTITY)) {
            this.tracker = data.getStringExtra(TrackConsts.TRACKER);
            this.entityName = data.getStringExtra(TrackConsts.ENTITY);
            tvStaffName.setText(this.tracker);
        }

        this.entities.clear();
        this.entities.add(entityName);

        clearLatestPointOverlay();
        queryLatestPoint();
        queryEntityList();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        Bundle bundle = marker.getExtraInfo();

        // 如果bundle为空或者marker不可见，则过滤点击事件
        if (null == bundle || !marker.isVisible()) {
            return false;
        }

        String status = "";

        boolean onLine = bundle.getBoolean("onLine");

        trackAnalysisInfoLayout.titleText.setText(tracker);
        trackAnalysisInfoLayout.key1.setText(R.string.entity_status);

        if (onLine) {
            double speed = bundle.getDouble("speed");

            if (CommonUtil.isEqualToZero(speed)) {
                trackAnalysisInfoLayout.value1.setText(TrackConsts.IMMOBILE);
            } else {

                trackAnalysisInfoLayout.value1.setText(String.format(Locale.CHINA,
                        "%.2f" + " Km/小时", speed));
            }
        } else {
            trackAnalysisInfoLayout.value1.setText(TrackConsts.OFF_LINE);
        }


        trackAnalysisInfoLayout.key2.setText(R.string.entity_address);
        trackAnalysisInfoLayout.value2.setText(bundle.getString("address"));
        trackAnalysisInfoLayout.key3.setText(R.string.entity_coord);
        trackAnalysisInfoLayout.value3.setText(bundle.getString("coord"));
        trackAnalysisInfoLayout.key4.setText(R.string.entity_latest_time);
        trackAnalysisInfoLayout.value4.setText(bundle.getString("time"));


        analysisMarker = marker;

        //创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
        InfoWindow trackAnalysisInfoWindow = new InfoWindow(trackAnalysisInfoLayout.mView, marker.getPosition(), -47);
        //显示InfoWindow
        mapUtil.baiduMap.showInfoWindow(trackAnalysisInfoWindow);

        return false;
    }

    @Override
    public void updateLatestPoint(LatLng newPoint) {

        if (null != mapUtil) {
            mapUtil.updateStatus(newPoint, false);
        }
    }

    @Override
    public void showEntities(List<EntityInfo> entities) {
        markers.clear();

        handleOverlays(markers, entities);
    }


    private void handleOverlays(List<Marker> markers,
                                List<? extends EntityInfo> entityInfoes) {
        if (null == markers || null == entityInfoes) {
            return;
        }

        for (EntityInfo info : entityInfoes) {

            LatestLocation point = info.getLatestLocation();
            OverlayOptions overlayOptions = new MarkerOptions()
                    .position(MapUtil.convertTrace2Map(point.getLocation()))
                    .icon(BitmapUtil.bmGcoding).zIndex(9).draggable(true);
            Marker marker = (Marker) mapUtil.baiduMap.addOverlay(overlayOptions);
            Bundle bundle = new Bundle();

            long modifytime = CommonUtil.toTimeStamp(info.getModifyTime());
            if (CommonUtil.getCurrentTime() - modifytime >= TrackConsts.OFF_LINE_TIME) {
                bundle.putBoolean("onLine", false);
            } else {
                bundle.putBoolean("onLine", true);
            }


            String coord = String.format(Locale.CHINESE, "%.6f,%.6f", point.getLocation().getLatitude(), point.getLocation().getLongitude());

            bundle.putString("time", info.getModifyTime());
            bundle.putDouble("speed", point.getSpeed());
            bundle.putString("address", "");
            bundle.putString("coord", coord);

            marker.setExtraInfo(bundle);
            markers.add(marker);
        }

        handleMarker(markers);
    }

    /**
     * 处理marker
     *
     * @param markers
     */
    private void handleMarker(List<Marker> markers) {
        if (null == markers || markers.isEmpty()) {
            return;
        }
        for (Marker marker : markers) {
            marker.setVisible(true);
        }

        if (markers.contains(analysisMarker)) {
            mapUtil.baiduMap.hideInfoWindow();
        }
    }


    /**
     * 清除最新位置覆盖物
     */
    public void clearLatestPointOverlay() {
        clearOverlays(markers);
    }

    private void clearOverlays(List<Marker> markers) {
        if (null == markers) {
            return;
        }

        if (markers.contains(analysisMarker)) {
            mapUtil.baiduMap.hideInfoWindow();
        }

        for (Marker marker : markers) {
            marker.remove();
        }
        markers.clear();
    }


    @Override
    protected void onPause() {
        super.onPause();
        mapUtil.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapUtil.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (null != trackAnalysisInfoLayout) {
            trackAnalysisInfoLayout = null;
        }

        clearLatestPointOverlay();

        mapUtil.clear();

    }


}
